import React, { useEffect, useState } from 'react';
import {
  Table, Card, Input, Select, Button, Space, Tag,
  Modal, Form, message, Tooltip, Row, Col, Avatar,
  Popconfirm
} from 'antd';
import {
  SearchOutlined, UserOutlined, LockOutlined,
  EditOutlined, DeleteOutlined, PlusOutlined
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import {
  setUsers,
  setFilters,
  setLoading
} from '../../store/userManagementSlice';
import adminApi from '../../api/adminApi';

const { Option } = Select;
const { confirm } = Modal;

const UserManagement = () => {
  const dispatch = useDispatch();
  const { users = [], loading = false, filters = {} } = useSelector(state => state.userManagement || {});
  const [selectedUser, setSelectedUser] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    loadUsers();
  }, [filters]);

  const loadUsers = async () => {
    try {
      dispatch(setLoading(true));
      const data = await adminApi.getUsers();
      dispatch(setUsers(data || []));
    } catch (error) {
      message.error(`加载用户列表失败: ${error.message || '未知错误'}`);
      dispatch(setUsers([]));
    } finally {
      dispatch(setLoading(false));
    }
  };

  const handleDelete = async (userId) => {
    try {
      await adminApi.deleteUser(userId);
      message.success('用户删除成功');
      loadUsers();
    } catch (error) {
      message.error(`删除失败: ${error.message || '未知错误'}`);
    }
  };

  const handleStatusChange = async (userId, status) => {
    try {
      await adminApi.updateUser(userId, { status });
      message.success('用户状态更新成功');
      loadUsers();
    } catch (error) {
      message.error(`状态更新失败: ${error.message || '未知错误'}`);
    }
  };

  const handleRoleChange = async (userId, role) => {
    try {
      await adminApi.updateUser(userId, { role });
      message.success('用户角色更新成功');
      loadUsers();
    } catch (error) {
      message.error(`角色更新失败: ${error.message || '未知错误'}`);
    }
  };

  const handleResetPassword = (userId) => {
    confirm({
      title: '确认重置密码？',
      content: '重置后将发送新密码到用户邮箱',
      onOk: async () => {
        try {
          await adminApi.updateUser(userId, { resetPassword: true });
          message.success('密码重置成功，新密码已发送至用户邮箱');
        } catch (error) {
          message.error(`密码重置失败: ${error.message || '未知错误'}`);
        }
      }
    });
  };

  const handleEditUser = async (values) => {
    try {
      if (selectedUser) {
        await adminApi.updateUser(selectedUser.id, values);
        message.success('用户信息更新成功');
        setIsModalVisible(false);
        loadUsers();
      }
    } catch (error) {
      message.error(`更新失败: ${error.message || '未知错误'}`);
    }
  };

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text, record) => (
        <Space>
          <Avatar icon={<UserOutlined />} src={record.avatar} />
          {text}
        </Space>
      ),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role, record) => (
        <Select
          value={role}
          onChange={(value) => handleRoleChange(record.id, value)}
          style={{ width: 120 }}
        >
          <Option value="student">学员</Option>
          <Option value="teacher">讲师</Option>
          <Option value="admin">管理员</Option>
        </Select>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => (
        <Select
          value={status}
          onChange={(value) => handleStatusChange(record.id, value)}
          style={{ width: 100 }}
        >
          <Option value="active">
            <Tag color="success">正常</Tag>
          </Option>
          <Option value="inactive">
            <Tag color="default">禁用</Tag>
          </Option>
          <Option value="pending">
            <Tag color="warning">待验证</Tag>
          </Option>
        </Select>
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Tooltip title="编辑">
            <Button
              icon={<EditOutlined />}
              onClick={() => {
                setSelectedUser(record);
                form.setFieldsValue(record);
                setIsModalVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="重置密码">
            <Button
              icon={<LockOutlined />}
              onClick={() => handleResetPassword(record.id)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个用户吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button icon={<DeleteOutlined />} danger />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div className="user-management-container">
      <Card>
        <Row gutter={[16, 16]} className="filter-row">
          <Col xs={24} sm={8} md={6}>
            <Input
              placeholder="搜索用户名/邮箱"
              prefix={<SearchOutlined />}
              onChange={e => dispatch(setFilters({ ...filters, searchQuery: e.target.value }))}
            />
          </Col>
          <Col xs={12} sm={6} md={4}>
            <Select
              placeholder="角色筛选"
              style={{ width: '100%' }}
              allowClear
              onChange={value => dispatch(setFilters({ ...filters, role: value }))}
            >
              <Option value="student">学员</Option>
              <Option value="teacher">讲师</Option>
              <Option value="admin">管理员</Option>
            </Select>
          </Col>
          <Col xs={12} sm={6} md={4}>
            <Select
              placeholder="状态筛选"
              style={{ width: '100%' }}
              allowClear
              onChange={value => dispatch(setFilters({ ...filters, status: value }))}
            >
              <Option value="active">正常</Option>
              <Option value="inactive">禁用</Option>
              <Option value="pending">待验证</Option>
            </Select>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={selectedUser ? "编辑用户" : "添加用户"}
        visible={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          setSelectedUser(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          onFinish={handleEditUser}
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;